//
//  MantisGCDTimer.m
//  Runner
//
//  Created by iosdeveloper on 2020/8/30.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "MantisGCDTimer.h"

static const NSString * GCDTIMER;
//记载一共多少个计时器
static int currentGCDTimerCount = 0;
//定时器
static dispatch_source_t timerContainer[100] = {};
@implementation MantisGCDTimer

+ (void)delayTime:(NSTimeInterval)delay withBlock:(ExeBlock)task{
  
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    if(task) task();
  });
  
}

+ (void)backgroundDelayTime:(NSTimeInterval)delay withBlock:(ExeBlock)task{
  
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [self delayTime:delay withBlock:task];
  });
  
}

+ (int)repeatWithDuration:(NSTimeInterval)duration
               repeatTimes:(int)repeatTimes
                  withTask:(ExeBlock)task
                  finished:(ExeBlock)finished{
  __block int GCDTimerCount = 0;
  [self repeatWithDuration:duration withTask:^(){
    GCDTimerCount++;
    if(task) task();
  } Cancle:^BOOL{
    if(GCDTimerCount>=repeatTimes-1){
      if(finished)finished();
      return YES;
    }
    return NO;
  }];
  return currentGCDTimerCount;
}

+ (int)repeatWithDuration:(NSTimeInterval)duration
                  withTask:(ExeBlock)task
                    Cancle:(CancleBlock)cancle{
  
  @synchronized (GCDTIMER) {
    
    currentGCDTimerCount++;
    dispatch_queue_t queue = dispatch_queue_create("timer", DISPATCH_QUEUE_CONCURRENT);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, duration * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
      if(task) task();
      if(cancle){
        if(cancle()) dispatch_source_cancel(timer);
      }
    });
    timerContainer[currentGCDTimerCount] = timer;
    dispatch_resume(timer);
    return currentGCDTimerCount;
    
  }
  
}

+ (int)backgroundRepeatWithDuration:(NSTimeInterval)duration
                         repeatTimes:(int)repeatTimes
                            withTask:(ExeBlock)task
                            finished:(ExeBlock)finished{
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [self repeatWithDuration:duration repeatTimes:repeatTimes withTask:task finished:finished];
  });
  return currentGCDTimerCount;
}

+ (int)backgroundRepeatWithDuration:(NSTimeInterval)duration
                            withTask:(ExeBlock)task
                              Cancle:(CancleBlock)cancle{
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [self repeatWithDuration:duration withTask:task Cancle:cancle];
  });
  return currentGCDTimerCount;
}

+ (void)stopGCDTimerWithID:(int)timerID{
  if(timerID>currentGCDTimerCount) return;
  dispatch_source_t timer = timerContainer[timerID];
  if(timer)
  dispatch_source_cancel(timer);
}


@end
